package org.example.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.common.ResponseEntity;
import org.example.dto.LoginDTO;
import org.example.dto.RegisterDTO;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**发送验证码**/
    @PostMapping("/send-verify-code")
    public ResponseEntity sendVerifyCode(@RequestParam String email){
        boolean result = userService.sendVerifyCode(email);
        if (result) {
            log.info("验证码发送成功，邮箱: {}", email);
            return ResponseEntity.ok("验证码发送成功");
        } else {
            return ResponseEntity.fail("验证码发送失败");
        }
    }
    
    /**注册**/
    @PostMapping("/register")
    public ResponseEntity addUser(RegisterDTO registerDTO){
        boolean result = userService.register(registerDTO);
        if (result) {
            return ResponseEntity.ok("注册成功");
        } else {
            return ResponseEntity.fail("注册失败，验证码错误或已过期");
        }
    }
    
    /**登录**/
    @PostMapping("/login")
    public ResponseEntity login(LoginDTO loginDTO){
        String token = userService.login(loginDTO.getEmail(), loginDTO.getPassword());
        if (token != null) {
            Map<String, String> data = new HashMap<>();
            data.put("token", token);
            return ResponseEntity.ok(data, "登录成功");
        } else {
            return ResponseEntity.fail("登录失败，用户名或密码错误");
        }
    }
}